package org.example.twoTree;

/**
 * 二叉树的增删查
 */
public class TwoTreeApi {

    TwoTree root;

    public TwoTreeApi(TwoTree root) {
        this.root = root;
    }

    public TwoTreeApi() {
    }
    //二叉树添加值
    public void add(int value) {
        if (root == null) {
            root = new TwoTree(value);
            return;
        }
        addNode(value,root);
    }

    public void addNode(int value, TwoTree root) {
        if (root == null || root.value == value) {
            return;
        }
        if (root.value > value) {
            if (root.leftNode == null) {
                root.leftNode = new TwoTree(value);
            }else {
                addNode(value,root.leftNode);
            }
        }else {
            if (root.rightNode == null) {
                root.rightNode = new TwoTree(value);
            }else {
                addNode(value, root.rightNode);
            }
        }
    }

    //二叉树删除值
    public TwoTree delete(int value) {
        return delete(root,value);
    }
    public TwoTree delete(TwoTree root, int value) {
        if (root == null) {
            return null;
        }
        if (root.value> value) {
            root.leftNode = delete(root.leftNode,value);
        }else if (root.value< value) {
            root.rightNode = delete(root.rightNode, value);
        }else  {
            if (root.leftNode == null) {
                return root.rightNode;
            }
            if (root.rightNode == null) {
                return root.leftNode;
            }
            TwoTree temp = root.rightNode;
            while (temp.leftNode != null) {
                temp = temp.leftNode;
            }
            root.value = temp.value;
            root.rightNode = delete(root.rightNode,root.value);
        }
        return  root;
    }


    //二叉树查询值
    public boolean find(int value) {
        return isExist(root,value);
    }

    private boolean isExist(TwoTree root, int value) {
        if (root == null) {
            return false;
        }else if (root.value == value) {
            return true;
        }else if(root.value> value){
            return isExist(root.leftNode, value);
        }else {
            return isExist(root.rightNode, value);
        }
    }

    public static void main(String[] args) {
        TwoTreeApi twoTreeApi = new TwoTreeApi();
        twoTreeApi.add(2);
        twoTreeApi.add(1);
        twoTreeApi.add(6);
        twoTreeApi.find(6);
        twoTreeApi.find(2);
        twoTreeApi.delete(2);
        System.out.println(twoTreeApi.root.value);
    }


}
